<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class UserAddress extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'name',
        'phone',
        'province',
        'city',
        'district',
        'address',
        'postal_code',
        'label',
        'is_default',
    ];

    protected $casts = [
        'is_default' => 'boolean',
    ];

    protected $appends = [
        'full_address',
    ];

    /**
     * 所属用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 获取完整地址
     */
    public function getFullAddressAttribute(): string
    {
        $parts = array_filter([
            $this->province,
            $this->city,
            $this->district,
            $this->address
        ]);
        
        return implode('', $parts);
    }

    /**
     * 设置为默认地址
     */
    public function setAsDefault(): void
    {
        // 先将该用户的其他地址设为非默认
        static::where('user_id', $this->user_id)
            ->where('id', '!=', $this->id)
            ->update(['is_default' => false]);
        
        // 设置当前地址为默认
        $this->update(['is_default' => true]);
    }
}
